package com.fanxl.flink.basic;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @description 单词统计
 * @author: fanxl
 * @date: 2022/1/10 0010 23:44
 */
public class BatchWCApp {

    public static void main(String[] args) throws Exception {
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        DataSource<String> dataSource = env.readTextFile("data/word.data");
        AggregateOperator<Tuple2<String, Integer>> sum = dataSource.flatMap(new PKFlatMap())
                .map(new PKMap())
                .groupBy(0)
                .sum(1);
        sum.print();
    }
}

class PKFlatMap implements FlatMapFunction<String, String> {
    @Override
    public void flatMap(String value, Collector<String> collector) throws Exception {
        String[] array = value.split(",");
        for (String word : array) {
            collector.collect(word.toLowerCase().trim());
        }
    }
}

class PKMap implements MapFunction<String, Tuple2<String, Integer>> {

    @Override
    public Tuple2<String, Integer> map(String value) throws Exception {
        return new Tuple2<>(value, 1);
    }
}
